﻿namespace Reviewer.Web.UI
{
    using System;
    using System.ComponentModel;
    using System.Configuration;
    using System.Reflection;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    public class MetadataItemEditPanel : WebControl, INamingContainer
    {
        protected Control concreteControl;
        protected Type concreteClass;

        [TypeConverter(typeof(TypeNameConverter))]
        [Themeable(false)]
        public Type DataType
        {
            get;
            set;
        }

        [DefaultValue("")]
        public virtual string ValidationGroup
        {
            get;
            set;
        }

        public override ControlCollection Controls
        {
            get
            {
                EnsureChildControls();
                return base.Controls;
            }
        }

        protected override void CreateChildControls()
        {
            Controls.Clear();

            this.concreteClass = typeof(MetadataItemEditPanel<>).MakeGenericType(DataType);
            this.concreteControl = (WebControl)Activator.CreateInstance(concreteClass);
            this.concreteControl.ID = (this.ID ?? this.Parent.ID) + "C";
            concreteClass.GetProperty("ValidationGroup").SetValue(this.concreteControl, this.ValidationGroup, null);
            this.Controls.Add(this.concreteControl);
        }

        public object Save()
        {
            EnsureChildControls();

            MethodInfo method = this.concreteClass.GetMethod("Save");
            return method.Invoke(this.concreteControl, null);
        }

        public void Reset()
        {
            EnsureChildControls();

            this.concreteClass.InvokeMember("Reset", BindingFlags.InvokeMethod, null, this.concreteControl, null);
        }

        public bool LoadItem(int itemId)
        {
            EnsureChildControls();

            MethodInfo method = this.concreteClass.GetMethod("LoadItem");
            return (bool)method.Invoke(this.concreteControl, new object[] { itemId });
        }
    }
}